package org.javaside.giveme.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.tencent.weibo.utils.OAuthClient;

import weibo4j.Weibo;
import weibo4j.WeiboException;
import weibo4j.http.AccessToken;
import weibo4j.http.RequestToken;

/**
 * 微薄的认证管理
 * 
 * @author xiaozhou
 *
 */
@Component
public class OAuthHolder {
	Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private WeiboConfig weiboConfig;
	
	/**
	 * 腾讯微薄 Request Token
	 * @return
	 * @throws Exception
	 */
	public com.tencent.weibo.beans.OAuth ttRequestToken() throws Exception{
		com.tencent.weibo.beans.OAuth oauth=new com.tencent.weibo.beans.OAuth();
		oauth.setOauth_callback(weiboConfig.getTtCallBackUrl());
		oauth.setOauth_consumer_key(weiboConfig.getTtConsumerKey());
		oauth.setOauth_consumer_secret(weiboConfig.getTtConsumerSecret());
		
		OAuthClient auth=new OAuthClient();
 
		// 获取request token
		oauth = auth.requestToken(oauth);
		return oauth;
	}
	
	/**
	 * 获取腾讯微薄Acess Token
	 * @param oauth
	 * @param verifier
	 * @return
	 * @throws Exception
	 */
	public com.tencent.weibo.beans.OAuth ttAcessToken(com.tencent.weibo.beans.OAuth oauth,String verifier) throws Exception{
		OAuthClient auth=new OAuthClient();
		oauth.setOauth_verifier(verifier);
        oauth = auth.accessToken(oauth);
        return oauth;
	}
	
	/**
	 * 获取sina RequestToken。
	 * @return
	 * @throws WeiboException
	 */
	public RequestToken requestToken() throws WeiboException{
		Weibo weibo = new Weibo();
		RequestToken requestToken = weibo.getOAuthRequestToken(weiboConfig.getSinaCallBackUrl());
		logger.info("Got request token.");
		logger.info("Request token: {}",requestToken.getToken());
		logger.info("Request token secret: {}",requestToken.getTokenSecret());
		return requestToken;
	}
	
	/**
	 * 获取sina AccessToken
	 * @param requestToken
	 * @param verifier
	 * @return
	 * @throws WeiboException
	 */
	public  AccessToken requstAccessToken(RequestToken requestToken,
			String verifier) throws WeiboException{
		Weibo weibo = new Weibo();
		AccessToken accessToken = weibo.getOAuthAccessToken(requestToken.getToken(), requestToken.getTokenSecret(), verifier);

		logger.info("Got access token.");
		logger.info("access token: " , accessToken.getToken());
		logger.info("access token secret: ",accessToken.getTokenSecret());
		return accessToken;
	}
}
